package cn.bxshey.configModule.ws;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @作者：不想说话而已
 * @Date：2024/3/8 22:15
 *
 * WebSocket处理器
 */
@Component
public class WsHandler extends AbstractWebSocketHandler {

    //存储WebSocketSession的以及其他信息的map集合
    private static final Map<String, SessionBean> sessionBeanMap;

    private static final AtomicInteger atomicInteger;


    static {
        sessionBeanMap = new ConcurrentHashMap<>();
        atomicInteger = new AtomicInteger(0);
    }

    //连接接立
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        SessionBean sessionBean = new SessionBean(session, atomicInteger.getAndIncrement());
        sessionBeanMap.put(session.getId(), sessionBean);
        System.err.println(sessionBeanMap.get(session.getId()).getId() + "连接打开");
        super.afterConnectionEstablished(session);
    }

    //连接关闭
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        System.err.println(sessionBeanMap.get(session.getId()).getId() + "关闭了连接");
    }

    //收到消息
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //收到内容
        System.err.println(sessionBeanMap.get(session.getId()).getId() + ":" + message.getPayload());
        super.handleTextMessage(session, message);
    }

    //处理错误
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //如果处于打开状态，就关闭socket
        if (session.isOpen()) {
            session.close();
        }
        //删除已连接的客户端idMap信息
        sessionBeanMap.remove(session.getId());
        super.handleTransportError(session, exception);
    }

//    //定时心跳发送，每4s发送一次
//    @Scheduled(fixedRate = 4000)
//    public void sendMsg() throws IOException {
//        NoticeDTO noticeDTO = new NoticeDTO();
//        noticeDTO.setSum(1);
//        noticeDTO.setTime(new Date());
//        noticeDTO.setTitle("测试消息");
//        noticeDTO.setTyped("ads");
//        ObjectMapper objectMapper = new ObjectMapper();
//        for (String key : sessionBeanMap.keySet()) {
//            sessionBeanMap.get(key).getSession().sendMessage(new TextMessage(objectMapper.writeValueAsBytes(noticeDTO)));
//        }
//        System.err.println("定时发送中");
//    }

    //自定义方法，获取session
    public Map<String, SessionBean> getSessionBeanMap(){
        return sessionBeanMap;
    }

}
